home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3268 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: Rezonet.net!news
  2. From: ray@ultimate-tech.com (Ray Dunn)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Please help ?!
  5. Date: 25 Jan 1996 00:11:58 GMT
  6. Organization: Ultimate Technographics Inc.
  7. Message-ID: <4e6hse$dvl@ns.RezoNet.NET>
  8. References: <4dm889$3hs@neptunus.pi.net> <4drnv1$cr@news.iag.net> <4drq5i$cr@news.iag.net>
  9. NNTP-Posting-Host: 204.19.230.7
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=US-ASCII
  12. X-Newsreader: WinVN 0.99.7
  13.  
  14. In referenced article, John R Buchan says...
  15. >>   cpy = (char *) malloc(MAXLEN);
  16. >
  17. >The cast is unnecessary and can hide errors.  You should remove it.
  18.  
  19. This is the second time I've seen this advice in the last five minutes 
  20. in the newsgroup.
  21.  
  22. Certainly the cast is unnecessary, and certainly *some* unnecessary 
  23. casts can hide errors, but casting the result of malloc can *never* 
  24. hide an error, because it's telling the compiler to do something it 
  25. would do anyway.
  26.  
  27. On the other hand, if by any chance "cpy" is not a "char *", but you 
  28. thought it was when you wrote the statement, then including the cast 
  29. will *catch* an error.
  30.  
  31. I'd go as far as to say that if the argument of malloc, calloc, 
  32. etc. contains a sizeof operator such that a number of elements of that 
  33. type are being allocated, then adding a cast to a pointer of the same 
  34. type to the malloc return is the *safest* thing you can do:
  35.  
  36.   fred = malloc(n * sizeof(int));
  37.  
  38. Oops - fred isn't an "int *" it's a "long *", but the compiler wont 
  39. issue any warnings, but in:
  40.  
  41.   fred = (int *)malloc(n * sizeof(int));
  42.  
  43. the compiler will issue an error.
  44.  
  45. -- 
  46. Ray Dunn (opinions are my own) | Phone: (514) 938 9050
  47. Montreal                       | Phax : (514) 938 5225
  48. ray@ultimate-tech.com          | Home : (514) 630 3749
  49.  
  50.